package com.nl.lib_core.tool.extends

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.widget.Toast
import me.jessyan.autosize.utils.AutoSizeUtils

/** 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.util.extends 类名: ContextExtends */

// ----------toast----------
fun Context.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
  Toast.makeText(this, text, duration).show()
}

fun Context.toast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
  Toast.makeText(this, resId, duration).show()
}

fun Context.centerToast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
  val t = Toast.makeText(this, resId, duration)
  t.setGravity(Gravity.CENTER, 0, 0)
  t.show()
}

// ----------尺寸转换----------

fun Context.dp2px(dpValue: Float): Int {
  // val scale = resources.displayMetrics.density
  // (dpValue * scale + 0.5f).toInt()
  return AutoSizeUtils.dp2px(AutoSizeUtils.getApplicationByReflect(), dpValue)
}

fun Context.px2dp(pxValue: Float): Int {
  val scale = resources.displayMetrics.density
  return (pxValue / scale + 0.5f).toInt()
}

fun Context.sp2px(spValue: Float): Float {
  // val scale = resources.displayMetrics.scaledDensity
  // (spValue * scale)
  return AutoSizeUtils.sp2px(this, spValue).toFloat()
}

fun Context.px2sp(pxValue: Float): Int {
  val scale = resources.displayMetrics.scaledDensity
  return (pxValue / scale + 0.5f).toInt()
}

// ----------屏幕尺寸----------

fun Context.getScreenWidth(): Int {
  return resources.displayMetrics.widthPixels
}

fun Context.getScreenHeight(): Int {
  return resources.displayMetrics.heightPixels
}

// ----------NetWork----------

/** 打开网络设置 */
fun Context.openWirelessSettings() {
  startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}

/** 网络是否连接 */
fun Context.isConnected(): Boolean {
  val info = this.getActiveNetworkInfo()
  return info.isConnected
}

/** 判断网络是否是移动数据 */
fun Context.isMobileData(): Boolean {
  val info = this.getActiveNetworkInfo()
  return (null != info && info.isAvailable && info.type == ConnectivityManager.TYPE_MOBILE)
}

/** 退回到桌面 */
fun Context.startHomeActivity() {
  val homeIntent = Intent(Intent.ACTION_MAIN)
  homeIntent.addCategory(Intent.CATEGORY_HOME)
  startActivity(homeIntent)
}

@SuppressLint("MissingPermission")
private fun Context.getActiveNetworkInfo(): NetworkInfo {
  val manager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
  return manager.activeNetworkInfo!!
}

/** 通过提供的资源文件的名称来获取当前资源文件的Id */
fun Context.getIdFromDrawable(resName: String): Int {
  val res: Resources = this.resources
  return res.getIdentifier(resName, "drawable", packageName)
}

fun Context.getColorResources(
    resId: Int,
    theme: Resources.Theme? = null,
): Int {
  return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    this.resources.getColor(resId, theme)
  } else {
    this.resources.getColor(resId)
  }
}

/** 拼接资源字符串 */
fun Context.getStringFormat(resId: Int, vararg args: String?): String {
  return resources.getString(resId, args)
}

// ----------获取当前是否是指定的系统版本----------

fun Context.hasFroyo(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO
}

fun Context.hasGingerbread(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
}

fun Context.hasHoneycomb(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
}

fun Context.hasHoneycombMR1(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1
}

fun Context.hasHoneycombMR2(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2
}

fun Context.hasIceCreamSandwich(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
}

fun Context.hasJellyBean(): Boolean {
  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
}

fun Context.aboveJellyBean(): Boolean {
  return Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN
}

/**
 * 获取当前APP版本号
 *
 * @return 返回APP版本号
 */
fun Context.getAppVersion(context: Context): Int {
  var version = 0
  try {
    version = context.packageManager.getPackageInfo(context.packageName, 0).versionCode
  } catch (e: PackageManager.NameNotFoundException) {
    e.printStackTrace()
  }
  return version
}

/**
 * 当前app的是否在运行
 *
 * @return false: 说明app不在当前系统的栈中; true:当前app正处于用户使用状态(包含在Home在后台)
 */
@SuppressLint("NewApi")
fun Context.isAppRunning(context: Context): Boolean {
  val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
  val runningTaskInfos = activityManager.getRunningTasks(100) ?: return false
  for (taskInfo in runningTaskInfos) if (context.packageName ==
      taskInfo.baseActivity!!.packageName) {
    return true
  }
  return false
}

/**
 * 判断当前Activity是否排在栈顶
 *
 * @return
 */
@SuppressLint("NewApi")
fun Context.isTopActivity(context: Context, clazz: Class<*>): Boolean {
  val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
  val runningTaskInfos = manager.getRunningTasks(1)
  return runningTaskInfos != null &&
      runningTaskInfos.isNotEmpty() &&
      clazz.name == runningTaskInfos[0].topActivity!!.className
}

fun getSerial(): String {
  //  return "A7YFBB1320000739"
  return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   // Build.getSerial()

    "A7YFBB1320000739"
  } else {
    Build.SERIAL
  }
}
